import { computed, onMounted, ref } from "vue"
import { options } from "@/components/search/options"

export const useSearch = () =>{
  // 绑定搜索框数据
  const data = ref<string>("")

  // placeholder
  const searchPlaceholdersIndex = ref(0)
  const searchPlaceholders = ["系统介绍", "授权原理", "授权对象", "更新日志", "开发文档", "版权声明", "隐私政策", "常见问题", "应用市场"]
  searchPlaceholdersIndex.value = Math.floor(Math.random() * searchPlaceholders.length)
  onMounted(() => {
    setInterval(() => {
      // 生成一个随机索引，确保与当前索引不同
      let randomIndex = searchPlaceholdersIndex.value
      while (randomIndex === searchPlaceholdersIndex.value) {
        randomIndex = Math.floor(Math.random() * searchPlaceholders.length)
      }

      searchPlaceholdersIndex.value = randomIndex
    }, 5000)
  })
  const placeholder = computed(() => {
    return searchPlaceholders[searchPlaceholdersIndex.value]
  })

  // 搜索结果
  const moreOptions = computed(() => {
    const filteredOptions = options
      .filter(item => item.content.includes(data.value))
      .map(item => {
        return {
          content: item.content,
          onClick: item.onClick
        }
      })
    if (filteredOptions.length === 0) {
      // 返回的数组为空
      filteredOptions.push({
        content: "暂无搜索结果",
        onClick: () => {
          console.log()
        }
      })
    }
    return filteredOptions
  })

  // 确认搜索
  const searchSubmit = () => {
    if(data.value.trim() === ""){
      data.value = document?.querySelector("input")?.getAttribute("placeholder") as string
    }
  }
  return{
    data,
    placeholder,
    moreOptions,
    searchSubmit
  }
}
